<?php

class cntrlprint implements viewController {

	private $area;
	private $side;
	private $dependencies = array("CSS" => array("print.css"), "JavaScript" => array(), "InlineJavaScript" => array());
	private $pageName = "PicBoard Print preparation";
	private $userObj;
	private $tools = "";
	private $cellMargin = 10;
	private $pdfOptions;
	private $m_outputFormat;
	private $m_outputMode = "PDF";

	public function __construct(user &$userObj, $id = ""){
	
		if( $userObj->getAccessLevel() == -1 ){
			// User is not logged in
			header("Location: home");
			exit;
		}	

		if(isset($_GET['act'])) parse_str( $_GET['act'] );
		
		// Setup the view
		if(isset($_GET['layout']) && isset($_GET['pageSize'])){
			// Printed from print dialog
			$this->pdfOptions['layout'] = ($_GET['layout'] == 1) ? "Portrait" : "Landscape";
			
			switch($_GET['pageSize']){
			
				case "1":
					$this->pdfOptions['size'] = "A4";
				break;
				
				case "2":
					$this->pdfOptions['size'] = "Legal";
				break;
				
				case "3":
					$this->pdfOptions['size'] = "Letter";
				break;
				
				// Other page layout options
				
				
				// Default to A4.
				default:
					$this->pdfOptions['size'] = "";
				break;
			
			
			}
		}
		
		$chartData = chart::getChart($userObj, $id);
				
		// Did we get the chart information successfully and is the user allowed to see it?
		if($chartData['status'] == "success"){			
			$this->generatePage($chartData);
		} else {
			header("Location: error?e=166");
		}
		
		// Side area.
		$this->side = "";
	}
	
	private function generatePage(array $chartData){
		// Main area template
		$this->area = new template("area.printgrid");
		
		// What print formatter are we using?
		$formatter = isset($_GET['formatter']) ? $_GET['formatter'] : "";
		
		if($formatter != ""){
		
			if(class_exists($formatter) && is_subclass_of($formatter, 'printFormatter')){
				$this->m_outputFormat = new $formatter();
			} else {
				throw new PicBoardException("Formatter argument is invalid");
			}
		
		} else {
			$this->m_outputFormat = new $chartData['data']['chart']['style'];
		}

		$this->cellMargin = $this->m_outputFormat->getMargin();

		// Are there any dependencies for this format?

		foreach($this->m_outputFormat->getDependencies() as $file){
			if(strpos($file, ".css") !== false){
				array_push($this->dependencies['CSS'], $file);
			}
			if(strpos($file, ".js") !== false){
				array_push($this->dependencies['JavaScript'], $file);
			}
		}
		
		// HORRIBLE REGEX
		//preg_match("/\.cell\s?{(?:(?:[^}]+height:\s?([0-9]{2,})[\w|%]{1,2};){1}[^}]+(?:[^}]+width:\s?([0-9]{2,})[\w|%]{1,2};[^}]+){1}[^}]+|(?:[^}]+width:\s?([0-9]{2,})[\w|%]{1,2};[^}]+){1}[^}]+(?:height:\s?([0-9]{2,})[\w|%]{1,2};[^}]+))[^}]/ism", file_get_contents(SYS_CSSDIR . "main.css"), $matches );
		
		$cellHeight = $this->m_outputFormat->getCellDefaultHeight();
		$cellWidth = $this->m_outputFormat->getCellDefaultWidth();
		
		// Used for odd-size cell calculation
		$cellHeightDiff = 0;
		$cellWidthDiff = 0;
		
		// Format the cells
		$cellOutput = "";
		$cellTemplate = new template("fragment.cell");
		
		$colDiff = 0;
		$rowDiff = 0;
		
		// Do we have a difference in format over actual chart?
		if($chartData['data']['chart']['columns'] != $this->m_outputFormat->getColumns() && $this->m_outputFormat->getColumns() != "" || $chartData['data']['chart']['rows'] != $this->m_outputFormat->getRows() && $this->m_outputFormat->getRows() != ""){
			$colDiff = $this->m_outputFormat->getColumns() - $chartData['data']['chart']['columns'];
			$rowDiff = $this->m_outputFormat->getRows() - $chartData['data']['chart']['rows'];
			// Positive values are additions, negative cause jumping to the next row.
		}
		
		$numCells = ($this->m_outputFormat->getRows() * $this->m_outputFormat->getColumns());
		
		foreach($chartData['data']['cells'] as $k => $cell){
			if($numCells != "" && $k == $numCells) break;
			$textClasses = ($cell['textLocation'] == "top") ? "ctext" : "ctbottom";

			$textStyles = "";	
			$textStyles .= ($cell['textAlignment'] == 'center') ? "" : "text-align:" . $cell['textAlignment'] . "; ";
			$textStyles .= ($cell['textSize'] == '16') ? "" : "font-size: " . $cell['textSize'] . "; ";
			$textStyles .= ($cell['textBold']) ? "font-weight: bold; " : "";
			$textStyles .= ($cell['textItalic']) ? "font-style: italic; " : "";
			$textStyles .= ($cell['textUnderline']) ? "text-decoration: underline; " : "";
			$textStyles .= ($cell['fontFace'] == "") ? "" : "font-family: " . $cell['fontFace'] . "; ";
			$textStyles .= "color: " . $cell['textColour'] . "; ";
			$textStyles .= "height:" . $cell['textHeight'] . "px; ";
		
			$textTmpl = new template("fragment.celltext");
			$textTmpl->replaceAll(array(
				"textclasses" => $textClasses,
				"textstyle" => $textStyles,
				"ctext" => $cell['text']
			));
			
			// What's the location of the text?
			if($cell['textLocation'] == 'top'){
				$cellTemplate->replace('ct1', $textTmpl);
				$cellTemplate->replace('ct2', '');
			} else {
				$cellTemplate->replace('ct2', $textTmpl);
				$cellTemplate->replace('ct1', '');
			}
			
			$imageLoc = ($cell['mulberryURL'] != "") ? $cell['mulberryURL'] : $cell['imageURL']; 
			
			$pattern = "/" . addcslashes(SYS_BASEURL, "/.") . "SVGProxy\.php\?r=/i";
			
			//$imageSRC = preg_replace($pattern, "http://", $imageLoc);
			//$imageSRC = preg_replace("/svg/i", "png", $imageSRC);
			$imageSRC = $imageLoc;
			$imageSRC = preg_replace("/wmf/i", "svg", $imageLoc);

			$imageSRC = preg_replace("/http:\/\/straight-street/", SYS_BASEURL . "SVGProxy.php?r=straight-street", $imageSRC);
			
			$browser = util::getBrowser();
			
			$image = ($imageLoc == "") ? "" : "<img src='" . $imageSRC . "' alt='symbol' />";
			
			if(array_key_exists("firefox", $browser) && isset($_GET['preview'])){
				if((int)$_GET['preview'] == 1) $image = ($imageLoc == "") ? "" : "<embed src='" . $imageSRC . "' alt='symbol' type='image/svg+xml'></embed>";
			}
			
			//$image = ($imageLoc == "") ? "" : "<embed src='" . $imageSRC . "' type='image/svg+xml'></embed>";
			//$image = ($imageLoc == "") ? "" : "<iframe src=\"" . $imageSRC . "\" width=\"100\" height=\"100\">";
			
						
			$cellStyle = "border-color:" . $cell['frameColour'] . "; ";
			$cellStyle .= "background-color:" . $cell['bgColour'] . "; ";
			
			$definedHeight = $cellHeight;
			
			// Custom height/width?
			if($this->m_outputFormat->getCellCount() >= $k){
				$cells = $this->m_outputFormat->getCells();
				$definedHeight = isset($cells[$k+1]['height']) ? $cells[$k+1]['height'] : $cellHeight;
				if($definedHeight != $cellHeight){
					$cellStyle .= "height: " . $definedHeight . "px; ";
					$cellHeightDiff += ($cellHeight - $definedHeight);
				}
				
				$definedWidth = isset($cells[$k+1]['width']) ? $cells[$k+1]['width'] : $cellWidth;
				if($definedWidth != $cellWidth){
					$cellStyle .= "width: " . $definedWidth . "px; ";
					$cellWidthDiff += ($cellHeight - $definedWidth);
				}
			}
			
			$imgHeight = $definedHeight - $cell['textHeight'] - 15;
			
			$cellTemplate->replaceAll(array(
				"image" => $image,
				"cellstyle" => $cellStyle,
				"imagestyle" => "height: " . $imgHeight . "px;",
				"i" => $k
			));
		
			$cellOutput .= $cellTemplate->get();
			
			// If the template specifies more cells than we have we need to inject some blank cells.
			
			if($colDiff > 0){
				// If we have columns to add we have to add a new cell for every row.
				
				// Are we at an insertion point?

				if(($k+1) % $chartData['data']['chart']['columns'] == 0){
					for($i=0; $i < $colDiff; $i++){
						// Insert a blank cell
						$cellOutput .= $this->blankCell($k . $i);
					}
				}
			}
			
			
			if($rowDiff > 0){
				// Are we at the last cell?
				if( ($k+1) == count($chartData['data']['cells']) ){
					for($i=0; $i < $rowDiff; $i++){
						for($x=0; $x < ($chartData['data']['chart']['columns'] + $colDiff); $x++){
							$cellOutput .= $this->blankCell($k . $i . $x);
						}
					}
				}
			}
			
			$cellTemplate->reset();
		}
		
		$this->area->replaceAll(array(
			"chartName" => $chartData['data']['chart']['name'],
			"width" => (($cellWidth + $cellWidthDiff) + ($this->cellMargin['x'] * 2)) * ($chartData['data']['chart']['columns'] + $colDiff) . "px",
			"height" => (($cellHeight + $cellHeightDiff) + ($this->cellMargin['y'] * 2)) * ($chartData['data']['chart']['rows'] + $rowDiff) . "px",
			"cells" => $cellOutput
		));	
		
		$this->pdfOptions["formatter"] = $this->m_outputFormat;
		
		// Print preview mode
		if(isset($_GET['preview'])) {
			$this->m_outputMode = "HTML";
			array_push($this->dependencies['JavaScript'], "printPreview.js");
		}		
		
		array_push($this->dependencies['InlineJavaScript'], "PicBoard.addLoadEvent(\"drawPrintGuide('" . get_class($this->m_outputFormat) . "');\");");
		
	}
	
	private function blankCell($i){
		$cellTemplate = new template("fragment.cell");
		$cellTemplate->replaceAll(array(
			"image" => "",
			"cellstyle" => "",
			"i" => "blank" + $i,
			"ct1" => "",
			"ct2" => ""
		));
		return $cellTemplate->get();
	}
	
	// Controller functions
	public function getSide(){
		return $this->side;
	}
	
	public function getArea(){
		return $this->area;
	}
	
	public function getDependencies(){
		return $this->dependencies;
	}
	
	public function getPageName(){
		return $this->pageName;	
	}
	
	public function getTools(){
		return $this->tools;
	}
	
	public function setRuntimeConfiguration(){
		// Switch the output render mode to PDF.
		return array("outputMode" => $this->m_outputMode, "PDFOptions" => $this->pdfOptions);
	}
	
}

?>